
import { useEffect, useState, useRef } from 'react';
import { viewUtils } from '@/utils/arcgis/index';
import { jsapi } from '@/utils/arcgis';


/**
 * zoom hook - zoom逻辑抽成hook
 *
 * @returns [isLoading, zoomIn, zoomOut] - zoom加载状态，zoomIn函数, zoomOut函数
 
 * @author leway
 * @date 2020-07-16
 * @beta
 */
function useZoom(): [boolean, () => void, () => void] {
  const [isLoading, setIsLoading] = useState(true);
  const vmRef = useRef<any>();

  useEffect(() => {
    init();
  }, []);

  async function init() {
    const view = await viewUtils.isViewReady();
    const [ViewModel] = await jsapi.load(['esri/widgets/Zoom/ZoomViewModel']);
    vmRef.current = new ViewModel({ view });
    setIsLoading(false);
  }

  function zoomIn() {
    if (!vmRef.current || vmRef.current.state !== 'ready' || !vmRef.current.canZoomIn) {
      return;
    }
    vmRef.current.zoomIn();
  }
  
  function zoomOut() {
    if (!vmRef.current || vmRef.current.state !== 'ready' || !vmRef.current.canZoomOut) {
      return;
    }
    vmRef.current.zoomOut();
  }

  return [isLoading, zoomIn, zoomOut];
}

export default useZoom;
